package com.servlet;

import com.bean.User;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet("/user.do")
public class UserServlet extends BaseServlet {

    protected void login(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.sendRedirect("/");
        response.setContentType("text/html;charset=UTF-8");
        String username = request.getParameter("username");
        String ip = request.getRemoteAddr();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = simpleDateFormat.format(new Date());
        //把登录成功的用户 直接添加到在线名单当中
        //从ServletContext中 获取在线名单
        List<User> onlineUsers = (List<User>) request.getServletContext().getAttribute("onlineUsers");
        if (onlineUsers != null) {
            //已存在在线名单
            if (onlineUsers.contains(new User(username))) {
                //如果名单中 已经存在该用户名
                request.setAttribute("message", "用户名" + username + "已存在，请勿重复登录");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
                return;
            }
        }
        //创建User对象
        User user = new User(username, ip, dateStr);
        user.setSession(request.getSession());
        request.getSession().setAttribute("user", user);
//        request.getRequestDispatcher("/userList.jsp").forward(request,response);
        response.sendRedirect(request.getContextPath() + "/userList.jsp");
    }

    protected void logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.getSession().removeAttribute("user");
        //1.销毁Session
        request.getSession().invalidate();
        //2.重定向回登录页面
        response.sendRedirect(request.getContextPath() + "/login.jsp");
    }

    protected void kick(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取被踢用户的用户名

        String username = request.getParameter("username");
        List<User> onlineUsers = (List<User>) request.getSession().getServletContext().getAttribute("onlineUsers");

        //2.回退到未登录的状态，相当于帮这个用户强制注销
        int index = onlineUsers.indexOf(new User(username));
        User user = onlineUsers.get(index);
        //1.权限
        String ip = user.getIp();
        if ("admin".equals(user.getUsername())) {
            HttpSession session = user.getSession();
            session.removeAttribute("user");
            session.invalidate();
            response.sendRedirect(request.getContextPath() + "/userList.jsp");
        } else {
            response.getWriter().write("没有权限踢人！");
        }

    }
}
